import dd from 'gdt-jsapi';
import api from '../../api/index'
import Calendar from '../../components/calendar'
import utils from '../../common/utils'
import {getUserInfo} from '../../common/common'
Page({
    data: {
        accountId: '',
        code: '',
        userInfo: {},
        deviceIndex: -1,
        deviceList: [],
        hourRange: [],
        minuteRange: [],
        timeRangeValue:'',// 'xx:xx-xx:xx'
        timeRangeValueIndex:[],// [x,x,x,x]
        timeRangeShow: false,
        deviceSelectIndex: [],
        deviceSelectShow: false,
        calendar: new Calendar(),
        year: 2024,
        month: 9,
        monthDayArray: [],
        selectDateItem: null,
        applyRemark: '',
        devicePlanObj: {},
        applyCategoryList: [],
        applyCategoryIndex: -1,
        applyCategorySelectIndex: [],
        applyCategorySelectShow: false,
        saveLoading: false,
        logStr: '',
    },
    async getApplyCategoryList(){
      console.log('getApplyCategoryList')
      this.data.logStr += '[getApplyCategoryList start]'
        let list = []
        try {
            const res = await api.getApplyCategoryList()
            if (res.data && res.data.length) {
                list = res.data
            }
        } catch(e) {
          this.data.logStr += '[getApplyCategoryList error]' + JSON.stringify(e)
          console.log(e)
        }
        this.data.logStr += '[getApplyCategoryList end]' + JSON.stringify(list)
        return list
    },
    async getDeviceList(){
      console.log('getDeviceList')
      this.data.logStr += '[getDeviceList start]'
        let list = []
        try {
            const res = await api.getDeviceList(1)
            if (res.data && res.data.length) {
                list = res.data
            }
        } catch(e){
          this.data.logStr += '[getDeviceList error]' + JSON.stringify(e)
          console.log(e)
        }
        this.data.logStr += '[getDeviceList end]' + JSON.stringify(list)
        return list
    },
    async getDevicePlanObj (deviceSn) {
        try {
            const res = await api.getDevicePlan(deviceSn)
            if (res.data) {
                this.data.devicePlanObj[deviceSn] = res.data
                this.setData({
                    devicePlanObj: this.data.devicePlanObj
                })
            }
        } catch(e) {}
    },
    async onLoad(query) {
        this.data.userInfo = await getUserInfo()
        this.setData({
            hourRange: Array.from({length: 24}, (item, i) => i),
            minuteRange: Array.from({length: 60}, (item, i) => {
                if (i < 10) {
                    return `0${i}`
                }
                return i
            }),
            year: this.data.calendar.year,
            month: this.data.calendar.month,
            monthDayArray: this.data.calendar.monthDayArray,
            userInfo: this.data.userInfo,
        })
    },
    async getAppInitData() {
      this.data.logStr += '[getAppInitData start]'
        dd.showLoading({
            text: "加载中", //提示信息
        })
        const deviceList = await this.getDeviceList()
        const applyCategoryList = await this.getApplyCategoryList()

        dd.hideLoading({})
        this.data.logStr += '[getAppInitData end]'
        this.setData({
          deviceList,
          applyCategoryList,
      })

    },
    onApplyCategoryChange(e){
        this.setData({
            applyCategoryIndex: e.detail.value,
        });
    },
    onDeviceChange(e) {
        const index = e.detail.value
        this.getDevicePlanObj(this.data.deviceList[index].deviceSn)
        this.setData({
            deviceIndex: index,
        });
    },
    onShowSelectTimeRange() {
        if (!this.data.timeRangeValue) {
            const date = new Date()
            const hour = date.getHours()
            const minute = date.getMinutes()
            this.data.timeRangeValueIndex = [hour, minute, hour, minute];
        } else {
            const range = this.data.timeRangeValue.split('-')
            const start = range[0].split(':')
            const end = range[1].split(':')
            this.data.timeRangeValueIndex = [Number(start[0]),Number(start[1]),Number(end[0]),Number(end[1])];
        }
        this.setData({
            timeRangeValueIndex: this.data.timeRangeValueIndex,
            timeRangeShow: true,
        })
    },
    onCancelSelectTimeRange(){
        this.setData({
            timeRangeShow: false,
        })
    },
    onConfirmSelectTimeRange(){
        const timeRangeValue = this.data.timeRangeValueIndex
        if (timeRangeValue[2] < timeRangeValue[0]) {
            dd.showToast({
                content: '结束时间需晚于开始时间',
                type: 'none'
            })
            return
        }
        if (timeRangeValue[2] === timeRangeValue[0] && timeRangeValue[3] <= timeRangeValue[1]) {
            dd.showToast({
                content: '结束时间需晚于开始时间',
                type: 'none'
            })
            return
        }
        this.data.timeRangeValue = `${timeRangeValue[0] < 10 ? '0'+timeRangeValue[0] : timeRangeValue[0]}:${timeRangeValue[1] < 10 ? '0'+timeRangeValue[1] : timeRangeValue[1]}-${timeRangeValue[2] < 10 ? '0'+timeRangeValue[2] : timeRangeValue[2]}:${timeRangeValue[3] < 10 ? '0'+timeRangeValue[3] : timeRangeValue[3]}`
        this.setData({
            timeRangeValue: this.data.timeRangeValue,
            timeRangeShow: false,
        })
    },
    onChangeTimeRange(e){
        this.data.timeRangeValueIndex = e.detail.value
    },
    onSelectDate(e){
        const item = e.target.dataset.item
        if (item.month !== this.data.calendar.month) {
            return
        }
        const index = Number(e.target.dataset.index)
        this.data.calendar.monthDayArray.forEach((md) => {
            md.active = false
        })
        this.data.calendar.monthDayArray[index].active = true
        this.data.selectDateItem = this.data.calendar.monthDayArray[index]
        this.setData({
            selectDateItem: this.data.selectDateItem,
            monthDayArray: this.data.calendar.monthDayArray,
        })
    },
    onShowDeviceSelect() {
        let index = 0
        if (this.data.deviceIndex > -1) {
            index = this.data.deviceIndex
        }
        this.setData({
            deviceSelectIndex: [index],
            deviceSelectShow: true
        })
    },
    onChangeDeviceSelect(e) {
        this.data.deviceSelectIndex = e.detail.value
    },
    onCancelSelectDevice() {
        this.setData({
            deviceSelectShow: false,
        })
    },
    onConfirmSelectDevice() {
        const index = this.data.deviceSelectIndex[0]
        this.getDevicePlanObj(this.data.deviceList[index].deviceSn)
        this.setData({
            deviceSelectShow: false,
            deviceIndex: index
        })
    },

    onShowApplyCategorySelect() {
        let index = 0
        if (this.data.applyCategoryIndex > -1) {
            index = this.data.applyCategoryIndex
        }
        this.setData({
            applyCategorySelectIndex: [index],
            applyCategorySelectShow: true
        })
    },
    onChangeApplyCategorySelect(e) {
        this.data.applyCategorySelectIndex = e.detail.value
    },
    onCancelSelectApplyCategory() {
        this.setData({
            applyCategorySelectShow: false,
        })
    },
    onConfirmSelectApplyCategory() {
        const index = this.data.applyCategorySelectIndex[0]
        this.setData({
            applyCategorySelectShow: false,
            applyCategoryIndex: index
        })
    },


    onPrevMonth() {
        this.data.calendar.prevMonth()
        this.setData({
            year: this.data.calendar.year,
            month: this.data.calendar.month,
            monthDayArray: this.data.calendar.monthDayArray,
        })
    },
    onNextMonth() {
        this.data.calendar.nextMonth()
        this.setData({
            year: this.data.calendar.year,
            month: this.data.calendar.month,
            monthDayArray: this.data.calendar.monthDayArray,
        })
    },
    onPrevYear() {
        this.data.calendar.prevYear()
        this.setData({
            year: this.data.calendar.year,
            month: this.data.calendar.month,
            monthDayArray: this.data.calendar.monthDayArray,
        })
    },
    onNextYear() {
        this.data.calendar.nextYear()
        this.setData({
            year: this.data.calendar.year,
            month: this.data.calendar.month,
            monthDayArray: this.data.calendar.monthDayArray,
        })
    },
    bindRemarkInput(e){
        this.setData({
            applyRemark: e.detail.value,
        })
    },
    getIntersection() {
        let intersectionArr = []
        const applyUseTimeRangeArr = this.data.timeRangeValue.split('-')
        const applyUseDate = `${this.data.selectDateItem.year}-${this.data.selectDateItem.monthStr}-${this.data.selectDateItem.dateStr}`
        if (applyUseTimeRangeArr && applyUseTimeRangeArr.length == 2) {
            const devicePlanObj = this.data.devicePlanObj
            const deviceSn = this.data.deviceList.find((de, index) => index === this.data.deviceIndex).deviceSn
            if (devicePlanObj[deviceSn] && devicePlanObj[deviceSn][applyUseDate]) {
                intersectionArr = utils.judgeCanUse(applyUseTimeRangeArr[0], applyUseTimeRangeArr[1], devicePlanObj[deviceSn][applyUseDate])
            }
        }
        return intersectionArr
    },
    async executeSubmit() {
        const deviceSn = this.data.deviceList.find((de, index) => index === this.data.deviceIndex).deviceSn
        const applyUseDate = `${this.data.selectDateItem.year}-${this.data.selectDateItem.monthStr}-${this.data.selectDateItem.dateStr}`
        const approveAccountIds = this.data.applyCategoryList.find((de, index) => index === this.data.applyCategoryIndex).approveAccountIds
        dd.showLoading({
            text: '申请中'
        })
        if (!this.data.userInfo.accountId) {
            this.data.userInfo = await getUserInfo()
        }
        api.apply({
            deviceSn,
            applyUseDate,
            applyUseTimeRange: this.data.timeRangeValue,
            applyAccountId: this.data.userInfo.accountId,
            approveAccountIdList: approveAccountIds,
            applyRemark: this.data.applyRemark || ''
        }).then((res) => {
            dd.hideLoading()
            if (res.code === 0) {
                dd.showToast({
                    content: '申请成功',
                    type: 'success'
                })
                this.setData({
                    timeRangeValueIndex: [],
                    timeRangeValue: '',
                })
                this.getDevicePlanObj(this.data.deviceList[this.data.deviceIndex].deviceSn)
            } else {
                dd.showToast({
                    content: res.message || '申请失败',
                    type: 'none'
                })
            }
        }).catch((e) => {
            dd.hideLoading()
            console.log(e)
            dd.showToast({
                content: '服务异常',
                type: 'none'
            })
        })
    },
    onSubmitApply(){
        if (this.data.deviceIndex === -1) {
            dd.showToast({
                content: '请选择设备',
                type: 'none'
            })
            return
        }
        if (this.data.applyCategoryIndex === -1) {
            dd.showToast({
                content: '请选择审批类型',
                type: 'none'
            })
            return
        }
        if (!this.data.timeRangeValue) {
            dd.showToast({
                content: '请选择使用时段',
                type: 'none'
            })
            return
        }
        if (!this.data.selectDateItem) {
            dd.showToast({
                content: '请选择使用日期',
                type: 'none'
            })
            return
        }
        const intersectionArr = this.getIntersection()
        if (intersectionArr.length) {
            dd.confirm({
                title: "温馨提示",
                message: `您申请的使用时段与已存在的【${intersectionArr.join(',')}】时段有冲突，确定继续申请吗?`,
                buttonLabels: [
                    "确定",
                    "取消"
                ],
            }).then(res => {
                if (res.buttonIndex === 0) {
                    this.executeSubmit()
                }
            }).catch(err => {})
        } else {
            this.executeSubmit()
        }
    },
    onReady() {
        // 页面加载完成
    },
    onShow() {
      this.data.logStr = '[onShow]'
        this.getAppInitData()
    },
    onHide() {
        // 页面隐藏
    },
    onUnload() {
        // 页面被关闭
    },
    onTitleClick() {
        // 标题被点击
    },
    onPullDownRefresh() {
        // 页面被下拉
    },
    onReachBottom() {
        // 页面被拉到底部
    },
    onShareAppMessage() {
        // 返回自定义分享信息
        return {
            title: 'My App',
            desc: 'My App description',
            path: 'pages/index/index',
        };
    },
});
